const moment = require("moment");

const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function randomString(length: number) {
  var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = length; i > 0; --i)
    result += str[Math.floor(Math.random() * str.length)];
  return result;
}

let myHandler = async function (event, context, callback, logger) {
  const { userId, name, meetingType, duration, startTime, remindTime, abstract } = event.body ? JSON.parse(event.body) : event

  logger.info("userId:", userId)
  logger.info("name:", name)
  logger.info("meetingType:", meetingType)
  logger.info("duration:", duration)
  logger.info("startTime:", startTime)
  logger.info("remindTime:", remindTime)
  logger.info("abstract", abstract)

  const meeting = clouddb.CloudDBZoneGenericObject.build("mc_meeting")
  const id = generateUUID()
  const code = randomString(5)
  const meetingJson = {
    id,
    name,
    meetingType,
    duration,
    startTime: new Date(moment(startTime, "YYYY/MM/DD HH:mm:ss").valueOf()),
    remindTime,
    createBy: userId,
    status: 0,
    createTime: new Date(),
    updateTime: new Date(),
    code,
    abstract
  }
  logger.info("入库数据:", meetingJson)

  for (const key in meetingJson) {
    if (![undefined, null].includes(meetingJson[key])) {
      meeting.addFieldValue(key, meetingJson[key], key === "id");
    }
  }

  logger.info("封装数据:", meeting)

  try {
    const upsertNum = await mCloudDBZone.executeUpsert(meeting);
    logger.info('upsertNum=>', upsertNum);
  } catch (error) {
    logger.info('upsertMeetingInfo=>', error)
  }

  callback({
    code: 200,
    desc: "成功",
    data: { id, code }
  });
};

export { myHandler };